import { Component, OnInit } from '@angular/core';
import { DomSanitizer, SafeResourceUrl } from '@angular/platform-browser';
import { FetchService } from '../../../core/net/fetch.service';
import { NzCascaderOption } from 'ng-zorro-antd';
import * as moment from 'moment';

@Component({
  selector: 'app-settlement',
  templateUrl: './settlement.component.html',
  styleUrls: ['./settlement.component.scss']
})
export class SettlementComponent implements OnInit {
    gateIds: string[] | null = null;
    contentTitle: string;
    year = new Date();
    serverUrl = (window as any).environment.reportUrl;
    iframeSrc: SafeResourceUrl;
    loading = true;
    pid: string;

    constructor(private fetchService: FetchService,
                private sanitizer: DomSanitizer) {
    }

    ngOnInit(): void {
        this.queryInfo();
    }

    loadGateData(node: NzCascaderOption, index: number): PromiseLike<void> {
        return new Promise(resolve => {
            const params = {
                pid: index < 0 ? '0' : node.value,
                pageSize: 10000
            };
            this.fetchService
                .post('plan/wrsReportRelation/list', params)
                .subscribe(res => {
                    node.children = res['list'].map(item => {
                        if (item['menu'] === 1) {
                            return {
                                value: item.id,
                                label: item.name,
                                isLeaf: true
                            };
                        } else {
                            return {
                                value: item.id,
                                label: item.name
                            };
                        }
                    });
                    resolve();
                });
        });
    }

    onGateChanges(ids: string[]): void {
        console.log(ids);
        if (!!ids.length) {
            this.pid = ids[ids.length - 1];
            this.fetchService
                .post('plan/wrsReportRelation/list', {
                    pid: ids[ids.length - 1],
                    pageSize: 10000
                })
                .subscribe(res => {
                    this.queryInfo();
                });
        } else {
            this.pid = null;
        }
    }

    queryInfo(): void {
        this.loading = true;
        const year = moment(this.year).format('YYYY');
        const token = localStorage.token;
        const link = `${this.serverUrl}preview?_t=6&_u=wrs:水费统计表.ureport.xml&pid=${this.pid}&y=${year}`;
        this.iframeSrc = this.sanitizer.bypassSecurityTrustResourceUrl(link);
    }

    iframeOnLoad(): void {
        this.loading = false;
    }

    openModal(): void {

    }
}
